using System;
using System.Linq;
using UnityEngine;

[System.Serializable]
public struct RandomWeightConfig
{
    public GameObject gobj;
    public float weight;
}

[CreateAssetMenu(fileName = "New Random Pool", menuName = "BubbleGame/New Random Pool")]
public class RandomObjectPool : ScriptableObject
{
    public RandomWeightConfig[] objects;

    public GameObject GetRandomObject()
    {
        if (objects == null || objects.Length == 0)
        {
            Debug.LogError("No objects configured in the pool.");
            return null;
        }

        float totalWeight = objects.Sum(item => item.weight);
        float randomValue = UnityEngine.Random.Range(0.0f, totalWeight);

        float cumulativeWeight = 0.0f;
        foreach (var item in objects)
        {
            cumulativeWeight += item.weight;
            if (randomValue <= cumulativeWeight)
            {
                return item.gobj;
            }
        }

        // Fallback to the last item in case of floating point precision issues
        return objects[objects.Length - 1].gobj;
    }
}